if(!require("EBImage")){
install.packages("BiocManager")
BiocManager::install("EBImage")
}
if(!require("R.matlab")){
install.packages("R.matlab")
}
if(!require("readxl")){
install.packages("readxl")
}
if(!require("dplyr")){
install.packages("dplyr")
}
if(!require("readxl")){
install.packages("readxl")
}
if(!require("ggplot2")){
install.packages("ggplot2")
}
if(!require("caret")){
install.packages("caret")
}
if(!require("glmnet")){
install.packages("glmnet")
}
if(!require("WeightedROC")){
install.packages("WeightedROC")
}
if(!require("gbm")){
install.packages("gbm")
}
if(!require("tidyverse")){
install.packages("tidyverse")
}
library(R.matlab)
library(readxl)
library(dplyr)
library(EBImage)
library(ggplot2)
library(caret)
library(glmnet)
library(WeightedROC)
library(gbm)
library(tidyverse)
set.seed(2020)
setwd(getwd())
Provide directories for training images. Training images and Training fiducial points will be in different subfolders.
train_dir <- "../data/train_set/" # This will be modified for different data sets.
train_image_dir <- paste(train_dir, "images/", sep="")
train_pt_dir <- paste(train_dir, "points/", sep="")
train_label_path <- paste(train_dir, "label.csv", sep="")
In this chunk, we have a set of controls for the evaluation experiments.
run.cv <- TRUE # run cross-validation on the training set
sample.reweight <- TRUE # run sample reweighting in model training
K <- 5 # number of CV folds
run.feature.train <- TRUE # process features for training set
run.test <- TRUE # run evaluation on an independent test set
run.feature.test <- TRUE # process features for test set
Using cross-validation or independent test set evaluation, we compare the performance of models with different specifications.
In this part, we tune parameters n.trees (total number of trees) and shrinkage (learning rate) for boosted decision stumps (Gradient Boosting Machine).
#GBM parameters
n.trees <- c(40,50,60,70) #40-70
shrinkage <- c(0.01,0.05,0.1,0.15) #0.01-1
#model_labels = paste("GBM with n.trees =", n.trees,"and shrinkage =",shrinkage)
#train-test split
info <- read.csv(train_label_path)
n <- nrow(info)
n_train <- round(n*(4/5), 0)
train_idx <- sample(info$Index, n_train, replace = F)
test_idx <- setdiff(info$Index, train_idx)
If you choose to extract features from images, such as using Gabor filter, R memory will exhaust all images are read together. The solution is to repeat reading a smaller batch(e.g 100) and process them.
n_files <- length(list.files(train_image_dir))
image_list <- list()
for(i in 1:100){
image_list[[i]] <- readImage(paste0(train_image_dir, sprintf("%04d", i), ".jpg"))
}
Fiducial points are stored in matlab format. In this step, we read them and store them in a list.
#function to read fiducial points
#input: index
#output: matrix of fiducial points corresponding to the index
readMat.matrix <- function(index){
return(round(readMat(paste0(train_pt_dir, sprintf("%04d", index), ".mat"))[[1]],0))
}
#load fiducial points
fiducial_pt_list <- lapply(1:n_files, readMat.matrix)
save(fiducial_pt_list, file="../output/fiducial_pt_list.RData")
The follow plots show how pairwise distance between fiducial points can work as feature for facial emotion recognition.
The third column is the distributions of vertical distances between right mouth corner(50) and the midpoint of the upper lip(52). For example, the distance of an happy face tends to be shorter than that of a sad face.
Figure1
feature.R should be the wrapper for all your feature engineering functions and options. The function feature( ) should have options that correspond to different scenarios for your project and produces an R object that contains features and responses that are required by all the models you are going to evaluate later.
feature.Rsource("../lib/feature.R")
tm_feature_train <- NA
if(run.feature.train){
tm_feature_train <- system.time(dat_train <- feature(fiducial_pt_list, train_idx))
save(dat_train, file="../output/feature_train.RData")
}else{
load(file="../output/feature_train.RData")
}
tm_feature_test <- NA
if(run.feature.test){
tm_feature_test <- system.time(dat_test <- feature(fiducial_pt_list, test_idx))
save(dat_test, file="../output/feature_test.RData")
}else{
load(file="../output/feature_test.RData")
}
Call the train model and test model from library.
train.R and test.R should be wrappers for all your model training steps and your classification/prediction steps.
train.Rtest.Rsource("../lib/train_baseline.R")
source("../lib/test_baseline.R")
source("../lib/cv_baseline.R")
#feature_train = dat_train[, -6007]
#label_train = dat_train$label
feature_train = as.matrix(dat_train[, -6007])
label_train = as.integer(dat_train$label)
if(run.cv){
mean.error_cv <- matrix(0, nrow = length(n.trees), ncol=length(shrinkage))
sd.error_cv <- matrix(0, nrow = length(n.trees), ncol=length(shrinkage))
mean.AUC_cv <- matrix(0, nrow = length(n.trees), ncol=length(shrinkage))
sd.AUC_cv <- matrix(0, nrow = length(n.trees), ncol=length(shrinkage))
for(i in 1:length(n.trees)){
cat("n.trees = ", n.trees[i], "\n")
for (j in 1:length(shrinkage)){
cat("shrinkage = ", shrinkage[j], "\n")
res_cv<- cv.function(feature_train,
label_train,
K,
n.trees[i],
shrinkage[j],
reweight = sample.reweight)
mean.error_cv[i,j]<-res_cv[1]
sd.error_cv[i,j]<-res_cv[2]
mean.AUC_cv[i,j]<-res_cv[3]
sd.AUC_cv[i,j]<-res_cv[4]
}
}
save(mean.error_cv, file="../output/mean.error_cv.RData")
save(sd.error_cv, file="../output/sd.error_cv.RData")
save(mean.AUC_cv, file="../output/mean.AUC_cv.RData")
save(sd.AUC_cv, file="../output/sd.AUC_cv.RData")
}else{
load("../output/mean.error_cv.RData")
load("../output/sd.error_cv.RData")
load("../output/mean.AUC_cv.RData")
load("../output/sd.AUC_cv.RData")
}
Visualize cross-validation results.
df.mean.error<-data.frame(mean.error_cv)%>%
setNames(shrinkage)%>%
mutate(n.trees=n.trees)%>%
pivot_longer(c(-n.trees),names_to = "shrinkage",values_to = "mean.error")
df.sd.error<-data.frame(sd.error_cv)%>%
setNames(shrinkage)%>%
mutate(n.trees=n.trees)%>%
pivot_longer(c(-n.trees),names_to = "shrinkage",values_to = "sd.error")
df.mean.AUC<-data.frame(mean.AUC_cv)%>%
setNames(shrinkage)%>%
mutate(n.trees=n.trees)%>%
pivot_longer(c(-n.trees),names_to = "shrinkage",values_to = "mean.AUC")
df.sd.AUC<-data.frame(sd.AUC_cv)%>%
setNames(shrinkage)%>%
mutate(n.trees=n.trees)%>%
pivot_longer(c(-n.trees),names_to = "shrinkage",values_to = "sd.AUC")
res_cvvv<-df.mean.error%>%mutate(sd.error=df.sd.error$sd.error,
mean.AUC=df.mean.AUC$mean.AUC,
sd.AUC=df.sd.AUC$sd.AUC)
save(res_cvvv, file="../output/res_cvvv.RData")
load("../output/res_cvvv.RData")
if(run.cv){
p1 <- res_cvvv%>%
ggplot(aes(x = n.trees, y = mean.error,
ymin = mean.error - sd.error, ymax = mean.error + sd.error)) +
geom_crossbar() +
facet_wrap(~shrinkage)+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
p2 <- res_cvvv %>%
ggplot(aes(x = as.factor(n.trees), y = mean.AUC,
ymin = mean.AUC - sd.AUC, ymax = mean.AUC + sd.AUC)) +
geom_crossbar() +
facet_wrap(~shrinkage)+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
print(p1)
print(p2)
}
n.trees_best <- as.numeric(res_cvvv[which.min(res_cvvv$mean.error),1])
shrinkage_best <- as.numeric(res_cvvv[which.min(res_cvvv$mean.error),2])
n.trees_best
## [1] 50
shrinkage_best
## [1] 0.15
# training weights
weight_train <- rep(NA, length(label_train))
for (v in unique(label_train)){
weight_train[label_train == v] = 0.5 * length(label_train) / length(label_train[label_train == v])
}
if (sample.reweight){
tm_train <- system.time(fit_train <- train(feature_train,label_train,
w = weight_train,
n.trees_best,shrinkage_best))
} else {
tm_train <- system.time(fit_train <- train(feature_train,label_train,
w=NULL,
n.trees_best,shrinkage_best))
}
save(fit_train, file="../output/fit_train.RData")
tm_test = NA
feature_test <- as.matrix(dat_test[, -6007])
if(run.test){
load(file="../output/fit_train.RData")
tm_test <- system.time(
{label_pred <- as.integer(test(fit_train,feature_test,
n.trees_best,shrinkage_best,
pred.type = 'link'));
prob_pred <- test(fit_train, feature_test,
n.trees_best,shrinkage_best,
pred.type = 'response')})
}
## reweight the test data to represent a balanced label distribution
label_test <- as.integer(dat_test$label)
weight_test <- rep(NA, length(label_test))
for (v in unique(label_test)){
weight_test[label_test == v] = 0.5 * length(label_test) / length(label_test[label_test == v])
}
accu <- mean(label_pred == label_test)
tpr.fpr <- WeightedROC(prob_pred, label_test, weight_test)
auc <- WeightedAUC(tpr.fpr)
cat("The accuracy of model: GBM with n.trees =", n.trees_best, "and shrinkage =",shrinkage_best,"is", accu*100, "%.\n")
## The accuracy of model: GBM with n.trees = 50 and shrinkage = 0.15 is 69.66667 %.
cat("The accuracy of model: GBM with n.trees =", n.trees_best, "and shrinkage =",shrinkage_best,"is", auc, ".\n")
## The accuracy of model: GBM with n.trees = 50 and shrinkage = 0.15 is 0.6835863 .
Prediction performance matters, so does the running times for constructing features and for training the model, especially when the computation resource is limited.
cat("Time for constructing training features=", tm_feature_train[1], "s \n")
## Time for constructing training features= 1.268 s
cat("Time for constructing testing features=", tm_feature_test[1], "s \n")
## Time for constructing testing features= 0.268 s
cat("Time for training model=", tm_train[1], "s \n")
## Time for training model= 33.51 s
cat("Time for testing model=", tm_test[1], "s \n")
## Time for testing model= 0.487 s